<template>
  <div class="video-edit-container">
    <!-- 视频展示区域 -->
    <div class="video-gallery">
      <h2>视频库</h2>
      <div class="video-grid" v-if="videoList.length>0">
        <div
            v-for="(video, index) in videoList"
            :key="video.id"
            class="video-item"
            :class="{
            'selected': isSelected(video.id),
            'selected-for-edit': editMode === 'cut' && selectedVideoId === video.id
          }"
            @click="handleVideoSelect(video.id)"
        >
          <video :src="videoPath+video.accessPath" @loadedmetadata="handleVideoLoaded(video.id, $event)"></video>
          <div class="video-info">
            <span>{{ video.fileName }}</span>
            <span>{{ formatDuration(video.duration) }}</span>
          </div>
        </div>
      </div>
      <el-empty description="暂无数据" v-else></el-empty>
    </div>

    <!-- 编辑模式选择 -->
    <div class="edit-mode-selector">
      <button
          @click="switchEditMode('cut')"
          :class="{ 'active': editMode === 'cut' }"
      >
        剪辑模式
      </button>
      <button
          @click="switchEditMode('concat')"
          :class="{ 'active': editMode === 'concat' }"
      >
        拼接模式
      </button>
    </div>

    <!-- 剪辑编辑器 -->
    <VideoCutEditor
        v-if="editMode === 'cut' && selectedVideo"
        ref="cutEditorRef"
        :video="selectedVideo"
        @generate="handleGenerateCut"
    />

    <!-- 拼接编辑器 -->
    <VideoConcatEditor
        v-if="editMode === 'concat' && selectedVideos.length > 0"
        ref="concatEditorRef"
        :videos="selectedVideos"
        @remove="handleRemoveVideo"
        @generate="handleGenerateConcat"
    />
  </div>
</template>

<script setup>
import {ref, computed, watch, defineProps, defineEmits, onMounted} from 'vue';
 import VideoCutEditor from './VideoCutEditor.vue';
import VideoConcatEditor from './VideoConcatEditor.vue';
import videoDataAPI from "../api/modules/videoData";
import {API_CONFIG, dataAPI} from "../api";
import {ElMessage} from "element-plus";

const props = defineProps({
  rowData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['close', 'save']);
const loading = ref(false);
const videoList = ref([]);
const videoUrl = ref(API_CONFIG.BASE_URL);
const videoPath =ref(API_CONFIG.IMAGE_URL);
const getVideoList = async () => {
  videoList.value=[]
  loading.value = true;
  try {
    const params = { dataId: props.rowData.dataId };
    const result = await videoDataAPI.getVideoList(params);
    if (result?.code === 0) {
      videoList.value = result.data || [];
      ElMessage.success(`加载了 ${videoList.value.length} 条视频`);
    } else {
      throw new Error(result?.msg || '获取数据失败');
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error(`加载数据失败: ${error.message}`);
    videoList.value = [];
  } finally {
    loading.value = false;
  }
};
// 添加刷新按钮和方法
const handleRefresh = async () => {
  await getVideoList();
  // 重置选择状态
  selectedVideoId.value = null;
  selectedVideos.value = [];
};
// 编辑模式
const editMode = ref('cut'); // 'cut' 或 'concat'

// 剪辑模式相关
const selectedVideoId = ref(null);
const cutEditorRef = ref(null);

// 拼接模式相关
const selectedVideos = ref([]);
const concatEditorRef = ref(null);

// 生成的文件
const generatedFile = ref(null);

// 计算属性
const selectedVideo = computed(() => {
  return videoList.value.find(v => v.id === selectedVideoId.value);
});

// 方法
const formatDuration = (seconds) => {
  if (!seconds) return '00:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  const ms = Math.floor((seconds % 1) * 100);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms.toString().padStart(2, '0')}`;
};

const formatFileSize = (mb) => {
  return `${mb} MB`;
};

const isSelected = (id) => {
  if (editMode.value === 'cut') {
    return selectedVideoId.value === id;
  } else {
    return selectedVideos.value.some(v => v.id === id);
  }
};

const handleVideoSelect = (id) => {
  selectedVideo.value={}
  if (editMode.value === 'cut') {
    selectedVideoId.value = id;
    selectedVideos.value = []; // 清空拼接选择
  } else {
    const index = selectedVideos.value.findIndex(v => v.id === id);
    if (index === -1) {
      if (selectedVideos.value.length < 16) {
        const video = videoList.value.find(v => v.id === id);
        if (video) {
          selectedVideos.value.push({...video});
        }
      }
    } else {
      selectedVideos.value.splice(index, 1);
    }
  }
};

const handleVideoLoaded = (id, event) => {
  const video = videoList.value.find(v => v.id === id);
  if (video) {
    video.duration = event.target.duration;
  }
};

const switchEditMode = (mode) => {
  editMode.value = mode;
  if (mode === 'cut' && selectedVideos.value.length === 1) {
    selectedVideoId.value = selectedVideos.value[0].id;
  }
};

const handleRemoveVideo = (index) => {
  selectedVideos.value.splice(index, 1);
};

const handleGenerateCut = (result) => {
  generatedFile.value = {
    name: `${selectedVideo.value.name}_剪辑_${formatTime(result.start)}_${formatTime(result.end)}.mp4`,
    type: 'cut',
    size: Math.floor(selectedVideo.value.size * (result.end - result.start) / selectedVideo.value.duration),
    url: '#'
  };
};

const handleGenerateConcat = () => {
  if (selectedVideos.value.length < 2) return;

  const totalSize = selectedVideos.value.reduce((sum, video) => sum + video.size, 0);

  generatedFile.value = {
    name: `拼接_${selectedVideos.value.length}个视频.mp4`,
    type: 'concat',
    size: totalSize,
    url: '#'
  };
};


// 暴露给父组件的方法
const reset = () => {
  selectedVideoId.value = null;
  selectedVideos.value = [];
  generatedFile.value = null;
  editMode.value = 'cut';
};

const getGeneratedFile = () => {
  return generatedFile.value;
};
// 暴露刷新方法给父组件
defineExpose({
  reset,
  getGeneratedFile,
  refresh: getVideoList  // 新增的刷新方法
});
onMounted(async () => {
  await getVideoList();
  selectedVideo.value={}
});
</script>

<style scoped>
.video-edit-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.video-gallery {
  margin-bottom: 30px;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.video-item {
  position: relative;
  border: 2px solid #ddd;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
}

.video-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.video-item.selected {
  border-color: #4CAF50;
}

.video-item.selected-for-edit {
  border-color: #2196F3;
}

.video-item video {
  width: 100%;
  height: 120px;
  object-fit: cover;
  background: #000;
}

.video-info {
  padding: 8px;
  display: flex;
  justify-content: space-between;
  background: #f5f5f5;
  font-size: 14px;
}

.edit-mode-selector {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 20px 0;
}

.edit-mode-selector button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background: #e0e0e0;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
}

.edit-mode-selector button.active {
  background: #2196F3;
  color: white;
}

.generated-result {
  margin-top: 30px;
  padding: 20px;
  border: 1px solid #4CAF50;
  border-radius: 5px;
  background: #e8f5e9;
}

.download-btn {
  padding: 10px 20px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 15px;
}

.download-btn:hover {
  background: #1976D2;
}
</style>
